package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo9SumScore {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("Demo9SumScore")

    val sc = new SparkContext(conf)

    val studentsRDD: RDD[String] = sc.textFile("data/students.txt")
    val scoresRDD: RDD[String] = sc.textFile("data/score.txt")

    //解析数据转换kv格式
    val stuKVRDD: RDD[(String, String)] = studentsRDD
      .map(_.split(","))
      .map { case Array(id, name, _, _, _) => (id, name) }


    val scoreKVRDD: RDD[(String, Double)] = scoresRDD
      .map(_.split(","))
      .map { case Array(id, _, score) => (id, score.toDouble) }

    //计算总分
    val sumScoreRDD: RDD[(String, Double)] = scoreKVRDD.reduceByKey(_ + _)

    //关联
    val joinRDD: RDD[(String, (String, Double))] = stuKVRDD.join(sumScoreRDD)

    //整理数据
    joinRDD.map {
      case (id: String, (name: String, score: Double)) => (name, score)
    }.foreach(println)


  }
}
